package com.sso.auth.service;

import com.sso.common.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义用户详情服务
 * 在实际项目中，这里应该从数据库中加载用户信息
 * 
 * @author SSO System
 * @since 2024-01-01
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final PasswordEncoder passwordEncoder;
    private final Map<String, User> users;

    public CustomUserDetailsService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
        this.users = createMockUsers();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = users.get(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        Collection<GrantedAuthority> authorities = user.getAuthorities().stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .accountExpired(false)
                .accountLocked(!user.getEnabled())
                .credentialsExpired(false)
                .disabled(!user.getEnabled())
                .build();
    }

    /**
     * 根据用户名获取用户信息
     * 
     * @param username 用户名
     * @return 用户信息
     */
    public User getUserByUsername(String username) {
        return users.get(username);
    }

    /**
     * 创建模拟用户数据
     * 在实际项目中，应该从数据库中加载
     */
    private Map<String, User> createMockUsers() {
        Map<String, User> userMap = new HashMap<>();

        // 管理员用户
        User admin = new User("admin", passwordEncoder.encode("123456"), "admin@company.com");
        admin.setId(1L);
        admin.setFullName("系统管理员");
        admin.setDepartment("信息技术部");
        admin.setPhone("13800138000");
        admin.setAuthorities(Set.of("ROLE_ADMIN", "ROLE_USER", "oa:all", "risk:all"));
        userMap.put("admin", admin);

        // OA 系统用户
        User oaUser = new User("oa_user", passwordEncoder.encode("123456"), "oa@company.com");
        oaUser.setId(2L);
        oaUser.setFullName("办公用户");
        oaUser.setDepartment("办公室");
        oaUser.setPhone("13800138001");
        oaUser.setAuthorities(Set.of("ROLE_USER", "oa:read", "oa:write"));
        userMap.put("oa_user", oaUser);

        // 风控系统用户
        User riskUser = new User("risk_user", passwordEncoder.encode("123456"), "risk@company.com");
        riskUser.setId(3L);
        riskUser.setFullName("风控专员");
        riskUser.setDepartment("风险管理部");
        riskUser.setPhone("13800138002");
        riskUser.setAuthorities(Set.of("ROLE_USER", "risk:read", "risk:write", "risk:manage"));
        userMap.put("risk_user", riskUser);

        // 普通用户
        User normalUser = new User("user", passwordEncoder.encode("123456"), "user@company.com");
        normalUser.setId(4L);
        normalUser.setFullName("普通用户");
        normalUser.setDepartment("业务部");
        normalUser.setPhone("13800138003");
        normalUser.setAuthorities(Set.of("ROLE_USER"));
        userMap.put("user", normalUser);

        return userMap;
    }

    /**
     * 获取所有用户列表（用于演示）
     * 
     * @return 用户列表
     */
    public List<User> getAllUsers() {
        return new ArrayList<>(users.values());
    }
} 